<?php

namespace App\Http\Controllers\Admin\Wechat\Manager\Material;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Wechat\Text;

class TextController extends AdminController
{

	/**
	 * 获取列表数据
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function getLists(Request $request){
		$pageIndex = (int)$request->input('page') ?  $request->input('page') : 1;
        $length    = (int)$request->input('length') ?  $request->input('length') : 10;
        $start     = ($pageIndex-1)*$length;

    	$where = [];
        $bannerModel = Text::where($where);
        if($name=$request->input('name')){
            $bannerModel = $bannerModel->where('name', 'like', "%$name%");
        }

    	$data['total'] = $bannerModel->count();
    	if($data['total']>0){
    		$data['result'] = $bannerModel->orderBy('name','desc')->orderBy('updated_at','desc')->skip($start)->take($length)->get()->toArray();
    	}
    	$this->ajaxJson(0,'',$data);
	}

	/**
	 * 获取单个数据
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	function getOne($id){
		$text = $this->_get_one($id);
		$this->ajaxJson(0,'',$text);
	}

	/**
	 * 更新文本
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
    function updateText(Request $request){
    	$id = $request->input('id');
    	if($id){
    		$text = $this->_get_one($id);
    	}else{
    		$text = new Text();
    	}
    	$text->name = $request->input('name');
    	$text->content = $request->input('content');
    	$text->cacheEmpty($id)->save();
    	$this->ajaxJson(0,'更新成功');
    }

    /**
     * 删除文本消息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function deleteOne($id){
    	$text = $this->_get_one($id);
    	$text->cacheEmpty($id)->delete();
    	$this->ajaxJson(0,'删除成功');
    }

    function _get_one($id){
    	$text = Text::find($id);
    	if(!$text){
    		$this->ajaxJson(1,'不存在的数据');
    	}
    	return $text;
    }
}
